package com.yamaha.bikemarket;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.PauseOnScrollListener;
import com.yamaha.bikemarket.api.API;
import com.yamaha.bikemarket.util.LogUtil;
import com.yamaha.bikemarket.util.SCStaticFunc;
import com.yamaha.bikemarket.util.Utils;

public class WantToBuyFragment extends AMyActivity implements TextWatcher,
		TextView.OnEditorActionListener {

	private ImageLoader imageLoader;
	private LayoutInflater inflater;
	private final static AsyncHttpClient client = new AsyncHttpClient();
	private EditText searchField;
	private MyAdapter adapter;
	private final List<JSONObject> list = new ArrayList<JSONObject>();
	private final List<JSONObject> filterdList = new ArrayList<JSONObject>();

	public WantToBuyFragment() {
		super(MenuType.WANT_TO_BUY);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wanttobuy_layout);

		searchField = (EditText) findViewById(R.id.search_field);
		searchField.addTextChangedListener(this);
		searchField.setOnEditorActionListener(this);

		inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		final DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
				.cacheInMemory().cacheOnDisc().build();
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				getApplicationContext()).defaultDisplayImageOptions(
				defaultOptions).build();
		if (null != imageLoader && imageLoader.isInited()) {
			imageLoader.destroy();
			imageLoader = null;
		}
		imageLoader = ImageLoader.getInstance();
		if (!imageLoader.isInited()) {
			imageLoader.init(config);
		}

		list.clear();

		final ImageButton newButton = (ImageButton) findViewById(R.id.wtb_new_button);
		newButton.setOnClickListener(this);

		setListenerForMenu();
	}

	@Override
	protected List<EditText> getEditTexts() {
		final List<EditText> list = new ArrayList<EditText>();
		list.add(searchField);
		return list;
	}

	@Override
	public void onStart() {
		super.onStart();

		adapter = new MyAdapter();

		final ListView listView = (ListView) findViewById(R.id.listview);
		listView.setAdapter(adapter);

		boolean pauseOnScroll = true; // or true
		boolean pauseOnFling = true; // or false
		PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader,
				pauseOnScroll, pauseOnFling);
		listView.setOnScrollListener(listener);

		adapter.setLoading(true);
	}

	@Override
	protected void onResume() {
		super.onResume();

		getData();
	}

	private void getData() {

		filterdList.clear();
		list.clear();

		final String userId = SCStaticFunc.getUserId(this);
		final RequestParams params = new RequestParams();
		params.put("user_id", userId);

		LogUtil.i("WantToBuyFragment", "Get Data Params : " + params.toString());

		client.post(API.GET_WANT_TO_BUY, params,
				new MyAsyncHttpResponseHandler(API.GET_WANT_TO_BUY, this) {

					@Override
					public void onSuccess(final String res) {
						super.onSuccess(res);
						try {
							final JSONObject object = new JSONObject(res);

							final boolean isSuccess = object
									.getBoolean("success");
							if (isSuccess) {

								final JSONArray yearList = object
										.getJSONArray("year");

								SCStaticFunc.setData(WantToBuyFragment.this,
										SCStaticFunc.YEAR, yearList);

								final JSONArray resList = object
										.getJSONArray("message");

								// Convert To java.util.List
								for (int i = 0; i < resList.length(); i++) {
									list.add(resList.getJSONObject(i));
								}

								filterdList.addAll(list);

								adapter.setLoading(false);
								adapter.notifyDataSetChanged();

							} else {
								final String msg = object.getString("message");

								Utils.showAlertDialog(WantToBuyFragment.this,
										"Error", msg);
							}

						} catch (JSONException e) {
							LogUtil.e("WantToBuyFragment", e.getMessage(), e);
						}

					}
				});
	}

	private static class ItemHolder {
		TextView dateTime;
		TextView brand;
		TextView model;
		TextView regYear;
		ImageView image1;
		ImageView image2;
		ImageView image3;
		ImageView image4;
		ImageView image5;
		ImageView image6;
		ImageButton editButton;
	}

	private final class MyAdapter extends BaseAdapter implements Filterable,
			View.OnClickListener {
		private boolean isLoading = true;

		public void setLoading(boolean isLoading) {
			this.isLoading = isLoading;
		}

		@Override
		public int getCount() {
			return (isLoading) ? 1 : filterdList.size();
		}

		@Override
		public Object getItem(int position) {
			return filterdList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public Filter getFilter() {

			final Filter filter = new Filter() {

				@Override
				protected FilterResults performFiltering(CharSequence constraint) {

					final List<JSONObject> tempList = new ArrayList<JSONObject>();

					FilterResults results = new FilterResults();

					Log.d("Filterd", "Constraint : " + constraint);

					if (constraint == null || constraint.length() == 0) {
						tempList.addAll(list);
					} else {

						constraint = constraint.toString().toLowerCase(
								Locale.UK);

						for (final JSONObject obj : list) {

							try {
								final String brandName = obj
										.getString("brand_name");
								final String modelName = obj
										.getString("model_name");

								Log.d("Filter Position", "Brand Name : "
										+ brandName + ", with : " + constraint);

								if (brandName != null) {
									if (brandName.toLowerCase(Locale.UK)
											.contains(constraint)) {
										tempList.add(obj);
										continue;
									}
								}

								if (modelName != null) {
									if (modelName.toLowerCase(Locale.UK)
											.contains(constraint)) {
										tempList.add(obj);
										continue;
									}

								}

							} catch (JSONException e) {
								Log.e("Filter Exception", e.getMessage(), e);
							}
						}

					}

					results.count = tempList.size();
					results.values = tempList;

					return results;
				}

				@SuppressWarnings("unchecked")
				@Override
				protected void publishResults(CharSequence constraint,
						FilterResults results) {

					filterdList.clear();
					filterdList.addAll((List<JSONObject>) results.values);
					notifyDataSetChanged();
				}

			};

			return filter;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (isLoading) {
				convertView = inflater.inflate(R.layout.loading_item, parent,
						false);
				convertView.setId(0x0123);
				return convertView;
			}

			if (convertView != null && convertView.getId() == 0x0123) {
				convertView = null;
			}

			ItemHolder holder;
			if (null == convertView) {
				convertView = inflater
						.inflate(R.layout.wtb_item, parent, false);
				convertView.setId(position);

				holder = new ItemHolder();
				holder.brand = (TextView) convertView
						.findViewById(R.id.wtb_brand);
				holder.model = (TextView) convertView
						.findViewById(R.id.wtb_model);
				holder.dateTime = (TextView) convertView
						.findViewById(R.id.wtb_datetime);
				holder.regYear = (TextView) convertView
						.findViewById(R.id.wtb_regyear);
				holder.image1 = (ImageView) convertView
						.findViewById(R.id.image1);
				holder.image2 = (ImageView) convertView
						.findViewById(R.id.image2);
				holder.image3 = (ImageView) convertView
						.findViewById(R.id.image3);
				holder.image4 = (ImageView) convertView
						.findViewById(R.id.image4);
				holder.image5 = (ImageView) convertView
						.findViewById(R.id.image5);
				holder.image6 = (ImageView) convertView
						.findViewById(R.id.image6);
				holder.editButton = (ImageButton) convertView
						.findViewById(R.id.wtb_editbutton);

				convertView.setTag(holder);

			} else {
				holder = (ItemHolder) convertView.getTag();
			}

			try {
				final JSONObject obj = list.get(position);

				holder.brand.setText("Brand : " + obj.getString("brand_name"));
				holder.model.setText("Model : " + obj.getString("model_name"));
				holder.regYear.setText("Reg Year : "
						+ obj.getString("reg_year"));
				holder.dateTime.setText(obj.getString("time"));

				holder.image1.setImageBitmap(null);
				holder.image2.setImageBitmap(null);
				holder.image3.setImageBitmap(null);
				holder.image4.setImageBitmap(null);
				holder.image5.setImageBitmap(null);
				holder.image6.setImageBitmap(null);
				holder.editButton.setOnClickListener(this);
				holder.editButton.setTag(obj);

				final ImageView[] imgView = { holder.image1, holder.image2,
						holder.image3, holder.image4, holder.image5,
						holder.image6 };

				final JSONArray pix = obj.getJSONArray("pix");
				for (int i = 0; i < pix.length(); i++) {

					final JSONObject pixItem = pix.getJSONObject(i);
					final JSONArray pixWTS = pixItem.getJSONArray("pix");

					if (pixWTS != null && pixWTS.length() > 0) {
						final String url = pixWTS.getString(0);

						if (url != null && url.length() > 0) {
							imageLoader.displayImage(url, imgView[i]);
						}
					}
				}

			} catch (JSONException e) {
				LogUtil.e("Want To Buy View", e.getMessage(), e);
			}

			convertView.setOnClickListener(this);

			return convertView;
		}

		@Override
		public void onClick(View v) {

			if (R.id.wtb_editbutton == v.getId()) {
				// Edit Button

				try {
					final JSONObject object = (JSONObject) v.getTag();
					final String temp = object.getString("temp");

					final Intent intent = new Intent(WantToBuyFragment.this,
							WantToBuyEditFragment.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
					intent.putExtra("temp", temp);
					intent.putExtra("detail", object.toString());
					startActivity(intent);

				} catch (JSONException e) {
					LogUtil.e("WantToBuyFragment", e.getMessage(), e);
				}
			} else {
				// View

				try {
					final ImageButton btn = (ImageButton) v
							.findViewById(R.id.wtb_editbutton);
					final JSONObject object = (JSONObject) btn.getTag();
					final String temp = object.getString("temp");

					final Intent intent = new Intent(WantToBuyFragment.this,
							WantToBuyImageGalleryFragment.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
					intent.putExtra("temp", temp);
					intent.putExtra("detail", object.toString());
					startActivity(intent);

				} catch (JSONException e) {
					LogUtil.e("WantToBuyFragment", e.getMessage(), e);
				}

			}
		}

	}

	@Override
	public void onClick(View v) {

		if (onMenuClick(v)) {
			return;
		}

		switch (v.getId()) {
		case R.id.wtb_new_button: {
			final Intent intent = new Intent(this, WantToBuyEditFragment.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
			startActivity(intent);
		}
			break;
		case R.id.wtb_editbutton: {
			final ImageButton btn = (ImageButton) v;
			final JSONObject obj = (JSONObject) btn.getTag();

			final Intent intent = new Intent(this, WantToBuyEditFragment.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
			startActivity(intent);
		}
			break;
		default: {
			final int position = v.getId();
			final JSONObject data = list.get(position);
			// SCStaticFunc.setData(data);
			// mainActivity.showFragment(MainActivity.WANT_TO_BUY_GALLERY,
			// true);
		}
		}
	}

	@Override
	public boolean onEditorAction(TextView v, int keyCode, KeyEvent event) {
		if ((keyCode == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN)
				|| (keyCode == EditorInfo.IME_ACTION_DONE)) {
			hideInputText();
			return true;
		}
		return false;
	}

	@Override
	public void afterTextChanged(Editable s) {
		adapter.getFilter().filter(searchField.getText().toString());
	}

	@Override
	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub

	}
}
